package email

import (
	"fmt"
	"gin_template/core/setting"
	"io"
	"io/ioutil"
	"net"
	"strings"
	"time"

	"go.uber.org/zap"

	"github.com/emersion/go-imap"
	id "github.com/emersion/go-imap-id"
	"github.com/emersion/go-imap/client"
	"github.com/emersion/go-message/mail"
)

var emailServerConfig = &setting.AppConf.EmailConfig

// 登录函数
func loginEmail(Eserver, UserName, Password string) (*client.Client, error) {
	dial := new(net.Dialer)
	dial.Timeout = time.Duration(3) * time.Second
	c, err := client.DialWithDialerTLS(dial, Eserver, nil)
	if err != nil {
		c, err = client.DialWithDialer(dial, Eserver) // 非加密登录
	}
	if err != nil {
		return nil, err
	}
	//登陆
	if err = c.Login(UserName, Password); err != nil {
		return nil, err
	}
	return c, nil
}

// parseEmail 解析文本类型邮件（附件类型邮件解析目前存在问题 TODO）
// 确保发件为utf-8
func parseEmail(mr *mail.Reader) (body []byte, fileMap map[string][]byte) {
	for {
		p, err := mr.NextPart()
		if err == io.EOF {
			//fmt.Println("=====err === eof", err)
			break
		} else if err != nil {
			//fmt.Println("=====err not nil", err)
			break
		}
		if p != nil {
			switch h := p.Header.(type) {
			case *mail.InlineHeader:
				//fmt.Println("文本邮件")
				body, err = ioutil.ReadAll(p.Body)
				if err != nil {
					//fmt.Println("read body err:", err.Error())
					zap.L().Error("read body err", zap.Error(err))
				}

			case *mail.AttachmentHeader:
				//fmt.Println("附件邮件")
				fileName, _ := h.Filename()
				fileContent, _ := ioutil.ReadAll(p.Body)
				fileMap[fileName] = fileContent
			}
		}
	}
	return
}

func GetSubscribeUser(Eserver, UserName, Password string) (subscribeUser []*mail.Address, err error) {
	zap.L().Info("开始获取收件箱邮件")
	subscribeUser = make([]*mail.Address, 0, 10)
	c, err := loginEmail(Eserver, UserName, Password)
	if err != nil {
		//log.Info("login:", err)
		zap.L().Error("login failed", zap.Error(err))
		return
	}
	idClient := id.NewClient(c)
	idClient.ID(
		id.ID{
			id.FieldName:    "IMAPClient",
			id.FieldVersion: "2.1.0",
		},
	)

	defer c.Close()
	mailboxes := make(chan *imap.MailboxInfo, 10)
	mailboxeDone := make(chan error, 1)
	go func() {
		mailboxeDone <- c.List("", "*", mailboxes)
	}()
	for box := range mailboxes {
		//只看收件箱
		if box.Name != "INBOX" {
			continue
		}

		mbox, err := c.Select(box.Name, false)
		// 选择收件箱
		if err != nil {
			fmt.Println("select inbox err: ", err)
			continue
		}
		if mbox.Messages == 0 {
			continue
		}

		// 选择收取邮件的时间段
		criteria := imap.NewSearchCriteria()
		// 收取1天之内的邮件
		criteria.Since = time.Now().Add(-1 * time.Hour * 12)
		// 按条件查询邮件
		ids, err := c.UidSearch(criteria)
		fmt.Println("当前查询条件下的邮件数量", len(ids))
		if err != nil {
			continue
		}
		if len(ids) == 0 {
			continue
		}
		seqset := new(imap.SeqSet)
		seqset.AddNum(ids...)
		sect := &imap.BodySectionName{Peek: true}

		messages := make(chan *imap.Message, 100)
		messageDone := make(chan error, 1)

		go func() {
			messageDone <- c.UidFetch(seqset, []imap.FetchItem{sect.FetchItem()}, messages)
		}()
		for msg := range messages {
			r := msg.GetBody(sect)
			mr, err := mail.CreateReader(r)
			if err != nil {
				fmt.Println(err)
				continue
			}
			header := mr.Header
			mailSubject, _ := header.Subject()
			mailDate, _ := header.Date()

			add, _ := header.AddressList("From")
			fmt.Println(add[0].Address, add[0].Name)
			fmt.Println(mailSubject, mailDate)
			body, _ := parseEmail(mr)
			content := string(body)
			//zap.L().Info("邮件内容", zap.String("content", content))
			isExist := strings.Index(content, "开启订阅")
			//fmt.Println("========", isExist)
			zap.L().Info("是否订阅", zap.Bool("isSubscribe", isExist > 0))
			//如果该用户发送的邮件内容中包含"【开启订阅】" 字样，认为用户成功开启天气邮件订阅功能
			if isExist > 0 {
				subscribeUser = append(subscribeUser, add[0])
			}
		}
	}
	return subscribeUser, nil
}
